<template>
  <PageContainer>
    <view>
      <Header title="报名详情" :is-box-shadow="false" />
      <Loading v-model="loading">
        <view style="background-color: #fff">
          <TopActivityInfo
            :cover-url="activityInfo?.coverUrl"
            :address="activityInfo?.address"
            :address-name="activityInfo?.addressName"
            :start-time="activityInfo?.startTime"
            :title="activityInfo?.title"
            :latitude="activityInfo?.latitude"
            :longitude="activityInfo?.longitude"
            :activity-status="activityInfo?.activityStatus"
            @click="toActivityDetail"
          />
        </view>
        <view class="pa-12">
          <RegisterInfoView
            :register-info="registerInfo"
            :activity-info="activityInfo"
            :applicant-info="applicantInfo"
            @refresh="refresh"
          >
            <template>
              <TButton
                v-if="getShowCancelRegister"
                text="取消报名"
                type="none"
                :icon="'\ue604'"
                :customStyle="{
                  display: 'inline-block',
                  backgroundColor: '#F2F3F5',
                  color: '#333333',
                }"
                custom-class="h-24 linh-24 br-12"
                @click="modalVisible = true"
              />
              <TButton
                text="详细信息"
                type="none"
                :icon="'\ue8bf'"
                :customStyle="{
                  display: 'inline-block',
                  backgroundColor: '#F2F3F5',
                  color: '#333333',
                  marginLeft: '24rpx',
                }"
                custom-class="h-24 linh-24 br-12"
                @click="toRegisterFormForm"
              />
              <TButton
                v-if="showVoucherBtn && posterUrl"
                text="保存凭证"
                type="none"
                :icon="'\ue6b3'"
                :customStyle="{
                  display: 'inline-block',
                  backgroundColor: '#F2F3F5',
                  color: '#333333',
                  marginLeft: '24rpx',
                }"
                custom-class="h-24 linh-24 br-12"
                @click.stop="handleSaveVoucher"
              />
            </template>
          </RegisterInfoView>

          <CellBox title="报名申请信息" :list="applicantInfo" />
          <CellBox v-if="signInfo.length" title="签到信息" :list="signInfo" />
        </view>

        <TButtonGroup
          v-if="showSignBtn && activityInfo?.isSign"
          :styles="{
            backgroundColor: '#fff',
            boxShadow: '0px -4rpx 24rpx 0px rgba(150, 151, 153, 0.16)',
          }"
        >
          <TButton class="gutter-btn" text="立即签到" type="primary" @click="handleToSign" />
        </TButtonGroup>
      </Loading>

      <RegisterVoucher
        v-if="showVoucherBtn && registerInfo && activityInfo"
        :avatar="registerInfo?.avatar"
        :person-name="registerInfo?.personName"
        :person-tel="registerInfo?.personTel"
        :activity-title="activityInfo?.title"
        :ticket-name="registerInfo?.ticketName"
        :consume-no="registerInfo?.consumeNo"
        @success="posterSuccess"
      />
    </view>
  </PageContainer>

  <ShowModal
    v-model="modalVisible"
    title="取消报名"
    content-width="100%"
    cancel-text="暂不取消"
    confirm-text="申请取消"
    confirm-color="#EA5E0E"
    :confirm-auto-close="false"
    @confirm="handleCancelRegister"
  >
    <template #content>
      <view class="pa-20" style="width: 100%">
        <view class="fz-14 mb-16" style="color: #969799">
          <text>活动主办方审核同意取消后，如有支付的活动费用将原路退回。</text>
        </view>
        <view style="background-color: #f2f3f5">
          <UniEasyinput v-model="cancelRemark" type="textarea" placeholder="请说明取消报名原因" />
        </view>
      </view>
    </template>
  </ShowModal>

  <CancelRegistrationRecord
    v-if="registerInfo?.cancelRecordId"
    v-model:visible="cancelRegistrationRecordVisible"
    :register-id="registerInfo?.id"
    type="user"
  />
</template>

<script setup lang="ts">
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import Loading from '@/components/Loading/index.vue';
  import TopActivityInfo from '../components/TopActivityInfo.vue';
  import RegisterInfoView from '../components/RegisterInfoView.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import RegisterVoucher from '../components/RegisterVoucher.vue';
  import CellBox, { type ListItem as CellBoxListItem } from '../components/CellBox.vue';
  import { computed, ref } from 'vue';
  import type { ActivityRegisterTicketUnion, ActivityShortDetailVo } from '@/api/order/types';
  import {
    ApprovalStatusEnum,
    SignTypeEnum,
    SignTypeEnumTextMap,
  } from '@/enums/activityStatusEnum';
  import type { ActivityRegisterDetail } from '@/router/types/modules';
  import { RegisterTypeText, getApprovalStatusText } from '@/api/activity/types';
  import { cancelActivityRegister, registerDetail } from '@/api/activity';
  import { navigateTo, onLoad } from '@/router';
  import { SignStatusEnum } from '@/enums/activityStatusEnum';
  import { ActivityStatusEnum } from '@/enums/activityStatusEnum';
  import { onPullDownRefresh, onShow } from '@dcloudio/uni-app';
  import { Toast } from '@/utils';
  import ShowModal from '@/components/ShowModal/index.vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import CancelRegistrationRecord from '../components/CancelRegistrationRecord.vue';
  import { formatMoney } from '@/utils/number';

  const loading = ref(true);
  const registerInfo = ref<ActivityRegisterTicketUnion>();
  const activityInfo = ref<ActivityShortDetailVo>();

  const applicantInfo = ref<CellBoxListItem[]>([]);
  const signInfo = ref<CellBoxListItem[]>([]);

  const cancelRegistrationRecordVisible = ref(false);

  let callback: ActivityRegisterDetail['callback'];

  onLoad<'activityRegisterDetail'>((op) => {
    callback = op.callback;
    __init(op.registerId);
  });

  const isRefreshOnShow = ref(false);
  onShow(() => {
    if (isRefreshOnShow.value) {
      refresh();
      isRefreshOnShow.value = false;
    }
  });

  // 获取报名详情
  async function __init(registerId?: number) {
    loading.value = true;
    const id = registerInfo.value?.id as number;
    const { activityRegisterUserTicketVo: registerInfoVo, activityShortDetailVo } =
      await registerDetail(registerId || id);
    registerInfo.value = registerInfoVo;
    activityInfo.value = activityShortDetailVo;

    const statusObj = getApprovalStatusText.get(registerInfoVo.approvalStatus);
    const personInfo = `${registerInfoVo.gmatName} ${registerInfoVo.gmatPhone}`;
    applicantInfo.value = [
      {
        label: '报名提交人',
        value: personInfo,
      },
      { label: '报名时间', value: registerInfoVo.createTime },
      {
        label: '报名状态',
        value: statusObj?.text,
        valueColor: statusObj?.color,
      },
      { label: '报名类型', value: registerInfoVo.ticketName },
    ];

    if (registerInfoVo.totalDiscountMoney > 0) {
      applicantInfo.value.push({
        label: `会员优惠`,
        value: `-${formatMoney({ money: registerInfoVo.totalDiscountMoney })}`,
      });
    }

    if (registerInfoVo.totalMoney > 0) {
      applicantInfo.value.push({
        label: '费用总价',
        value: formatMoney({ money: registerInfoVo.totalMoney }),
      });
      applicantInfo.value.push({
        label: '实付金额',
        value: formatMoney({ money: registerInfoVo.payMoney }),
        valueColor: '#EA5E0E',
      });
    }

    applicantInfo.value.push({
      label: '报名来源',
      value: RegisterTypeText[registerInfoVo.registerType],
    });

    if (
      registerInfoVo.approvalStatus !== ApprovalStatusEnum.UNDERREVIEW &&
      registerInfoVo.verifyTime &&
      registerInfoVo.registerType !== 'batch'
    ) {
      applicantInfo.value.push({
        label: '审核人',
        value: registerInfoVo.verifyName || (registerInfoVo.verifyTime ? '无需审核' : '--'),
      });
      applicantInfo.value.push({ label: '审核时间', value: registerInfoVo.verifyTime });
    }

    if (registerInfoVo.cancelRecordId) {
      applicantInfo.value.push({
        label: '取消报名记录',
        operation: {
          text: '查看详情',
          callback: () => {
            cancelRegistrationRecordVisible.value = true;
          },
        },
      });
    }

    if (registerInfoVo.approvalStatus !== ApprovalStatusEnum.PASSED) {
      if (registerInfoVo.cancelPersonName) {
        applicantInfo.value.push({
          label: '取消人',
          value: registerInfoVo.cancelPersonName,
        });
      }

      if (registerInfoVo.cancelTime) {
        applicantInfo.value.push({
          label: '取消时间',
          value: registerInfoVo.cancelTime,
        });
      }
    }

    if (registerInfoVo.approvalStatus === ApprovalStatusEnum.REJECT) {
      applicantInfo.value.push({ label: '审核说明', value: registerInfoVo.remarks });
    }

    if (registerInfoVo.signStatus === SignStatusEnum.YES_SIGN) {
      signInfo.value = [
        {
          label: '签到人',
          value: (() => {
            let str = '';
            if (registerInfoVo.replaceSignPersonName) {
              str = registerInfoVo.replaceSignPersonName+' ';
            }
            if (registerInfoVo.replaceSignPersonPhone) {
              str += registerInfoVo.replaceSignPersonPhone;
            }
            if (str) return str;
            return '--';
          })(),
        },

        {
          label: '签到状态',
          value: registerInfoVo.signStatus === SignStatusEnum.YES_SIGN ? '已签到' : '未签到',
          valueColor: registerInfoVo.signStatus === SignStatusEnum.YES_SIGN ? '#2878FF' : '#646566',
        },
        { label: '签到时间', value: registerInfoVo.signTime || '--' },
        { label: '签到方式', value: SignTypeEnumTextMap[registerInfoVo.signType] },
        { label: '手写签名', value: registerInfoVo.signImg, valueType: 'img' },
      ];
    }

    loading.value = false;
    uni.stopPullDownRefresh();
  }

  const showSignBtn = computed(() => {
    return (
      registerInfo.value?.approvalStatus === ApprovalStatusEnum.PASSED &&
      registerInfo.value.signStatus === SignStatusEnum.NO_SIGN &&
      (activityInfo.value?.activityStatus === ActivityStatusEnum.START ||
        activityInfo.value?.activityStatus === ActivityStatusEnum.REGISTRATION_UNDERWAY ||
        activityInfo.value?.activityStatus === ActivityStatusEnum.REGISTRATION_END)
    );
  });

  function handleToSign() {
    isRefreshOnShow.value = true;
    if (activityInfo.value?.manualSign) {
      navigateTo({
        name: 'activitySign',
        options: {
          activityId: activityInfo.value.activityId as number,
          equipmentNumber: '',
          signType: SignTypeEnum.SCAN_SIGN_IN_CODE,
        },
      });
    } else {
      navigateTo({
        name: 'signInResult',
        options: {
          activityId: activityInfo.value?.activityId as number,
          url: '',
          equipmentNumber: '',
          signType: SignTypeEnum.SCAN_SIGN_IN_CODE,
        },
      });
    }
  }

  function refresh() {
    callback?.();
    __init();
  }

  function toActivityDetail() {
    navigateTo({
      name: 'activityDetails',
      options: {
        id: activityInfo.value?.activityId as number,
      },
    });
  }

  const getShowCancelRegister = computed(() => {
    return (
      (registerInfo.value?.approvalStatus === ApprovalStatusEnum.PASSED ||
        registerInfo.value?.approvalStatus === ApprovalStatusEnum.UNDERREVIEW ||
        registerInfo.value?.approvalStatus === ApprovalStatusEnum.WAITPARTICIPATEIN) &&
      activityInfo.value?.activityStatus !== ActivityStatusEnum.END &&
      activityInfo.value?.activityStatus !== ActivityStatusEnum.CANCEL &&
      registerInfo.value?.signStatus !== SignStatusEnum.YES_SIGN
    );
  });

  const modalVisible = ref(false);
  const cancelRemark = ref<string>('');
  /** 取消报名 */
  function handleCancelRegister() {
    if (!cancelRemark.value) return Toast('请说明取消报名原因');
    cancelActivityRegister({
      registerId: registerInfo.value?.id as number,
      remarks: cancelRemark.value,
    })
      .then(() => {
        refresh();
        Toast('申请已提交');
      })
      .finally(() => (modalVisible.value = false));
  }

  /** 跳转报名表单详情 */
  function toRegisterFormForm() {
    navigateTo({
      name: 'activityRegisterForm',
      options: {
        id: registerInfo.value?.id as number,
        type: 'registerDetail',
      },
    });
  }

  const showVoucherBtn = computed(() => {
    if (!registerInfo.value) return false;
    const { approvalStatus, signStatus, consumeNo } = registerInfo.value;
    return (
      approvalStatus === ApprovalStatusEnum.PASSED &&
      signStatus === SignStatusEnum.NO_SIGN &&
      consumeNo
    );
  });

  const posterUrl = ref<string>();
  /** 分享图生成成功回调 */
  function posterSuccess(url: string) {
    posterUrl.value = url;
  }

  /** 显示凭证 */
  function handleSaveVoucher() {
    if (!posterUrl.value) return Toast('凭证生成失败, 请重试');
    uni.showShareImageMenu({
      path: posterUrl.value,
    });
  }

  onPullDownRefresh(() => __init());
</script>

<style scoped></style>
